package com.soloyogame.anitoys.business.web.controller.manage.channel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.soloyogame.anitoys.business.web.controller.BaseController;
import com.soloyogame.anitoys.business.web.controller.util.LoginUserHolder;
import com.soloyogame.anitoys.core.Services;
import com.soloyogame.anitoys.db.bean.User;
import com.soloyogame.anitoys.db.commond.Channel;
import com.soloyogame.anitoys.db.page.PagerModel;
import com.soloyogame.anitoys.service.ChannelService;
import com.soloyogame.anitoys.util.StringTool;

/**
 * 字典管理控制类
 * @author shaojian
 */
@Component
@RequestMapping("/manage/channel/")
public class ChannelAction extends BaseController<Channel> 
{
	private static final long serialVersionUID = 1L;
	private static final String page_toList = "/manage/channel/channelList";
	private static final String page_toAdd = "/manage/channel/editchannel";
    private static final String page_toEdit = "/manage/channel/editchannel";
    private final String page_toAddOrUpdate = "/manage/channel/addOrUpdate";
    
    public ChannelAction() 
	{
		 super.page_toList = page_toList;
	     super.page_toEdit = page_toAdd;
	     super.page_toAdd = page_toEdit;
	}
	
    @Autowired
	private ChannelService channelService;
    
    @Override
	 public Services<Channel> getService() 
	 {
	    return channelService;
	 }

	/**
     * 查询分页列表
     */
    @Override
   	protected void selectListAfter(PagerModel pager) 
    {
   		pager.setPagerUrl("selectList");
   	}
    
    /**
	 * 初始化区域树
	 * @return
	 */
    @RequestMapping(value = "channelTree")
	public String channelTree()
    {
		return "/manage/channel/channelTree";
	}
    
    /**
	 * 获得栏目树结构数据
	 * @return
	 * @throws IOException 
	 */
    @RequestMapping("getChannelTree")
    @ResponseBody
	public String getAreaTree(HttpServletRequest request) throws IOException
	{
    	Channel e = new Channel();
    	User u = LoginUserHolder.getLoginUser();
        e.setBusinessId(u.getBusinessId());
    	e.setParentId("0");
    	List<Channel> channelList = channelService.selectList(e);
    	// 创建菜单集合
    	List<Channel> root = new ArrayList<Channel>();
		// 循环添加菜单到菜单集合
		for(int i=0;i<channelList.size();i++)
		{
			Channel channel = channelList.get(i);
			List<Channel> children = new ArrayList<Channel>();
			if(channel.getParentId().equals("0"))
			{
				for (Channel channel1 : channelList) 
				{
					if(channel1.getParentId().equals(channel.getId()))
					{
						children.add(channel1);
					}
				}
				channel.setChildren(children);
				root.add(channel);
			}
		}
		JSONArray json = JSONArray.fromObject(root);
		String jsonStr = json.toString();
		return jsonStr;
	}
    
    /**
	 * 转到 添加/修改栏目 页面
	 * @return
	 * @throws Exception
	 */
    @RequestMapping("toAddOrUpdate")
	public String toAddOrUpdate(String id, ModelMap model) throws Exception
	{
    	Channel channel = new Channel();
    	channel.setId(id);
    	Channel e = channelService.selectOne(channel);
        model.addAttribute("e", e);
		return page_toAddOrUpdate;
	}
    
    /**
   	 * 添加主类/修改主类、添加子类
   	 * @return
   	 * @throws IOException
   	 */
    @RequestMapping(value = "doAddOrUpdate", method = RequestMethod.POST)
    @ResponseBody
   	public String doAddOrUpdate(HttpServletRequest request,@ModelAttribute("e") Channel e) throws IOException
   	{
       	if(StringTool.isNull(e.getId()))
       	{
       		User u = LoginUserHolder.getLoginUser();
            e.setBusinessId(u.getBusinessId());
       		channelService.insert(e);
       	}
       	else
       	{
       		String childrenid = request.getParameter("childrenid");
			String childrenparentId = request.getParameter("childrenparentId");
			String childrenchannelUrl = request.getParameter("childrenchannelUrl");
			String childrenchannelName = request.getParameter("childrenchannelName");
			String childrensortOrder = request.getParameter("childrensortOrder");
			User u = LoginUserHolder.getLoginUser();
	        e.setBusinessId(u.getBusinessId());
			channelService.update(e);
    		Channel children = new Channel();
    		children.setId(childrenid);
    		children.setParentId(childrenparentId);
    		children.setChannelUrl(childrenchannelUrl);
    		children.setChannelName(childrenchannelName);
    		children.setBusinessId(u.getBusinessId());
    		if(StringTool.isNotNull(childrensortOrder))
    		{
    			children.setSortOrder(Integer.valueOf(childrensortOrder));
    		}
    		if(StringTool.isNotNull(childrenchannelName))
    		{
    			channelService.insert(children);
    		}
       	}
   			return "0";
   	}
    
    /**
	 * 对树的删除操作
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
	public String delete(HttpServletRequest request) throws Exception
	{
		String ids = request.getParameter("ids");
		if(StringUtils.isBlank(ids))
		{
			throw new Exception("非法请求！");
		}
		logger.error("delete.ids="+ids+",deleteParent="+request.getParameter("deleteParent"));
		channelService.deletesChannelNode(ids,request.getParameter("deleteParent"));
		
		//删除成功返回1
		return "1";
	}
}